﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Logic.Handler;
using Logic.Protocal.MessagePool;

namespace DL.Net
{
    public class NetResponseByRequestMgr : Singleton<NetResponseByRequestMgr>
    {
        private NetAsyncMgr _netAsyncMgr = new NetAsyncMgr();
        private static readonly ResponseResultContainer ResponseResultContainer = ResponseResultContainer.Inst;
        private int _seq = 0;
        public string Host = "127.0.0.1";
        public int Post = 8080;
        
        // public int TestProjectID = 0;
        // public Dropdown Dropdown;
        // public Button Button;
        // public Text Text;
        protected override void Construct()
        {
            // Dropdown.onValueChanged.AddListener((x) =>
            // {
            //     TestProjectID = x;
            //     Debug.Log($"调整TestProjectID:{TestProjectID}");
            // });
            // Button.onClick.AddListener( () => Test());
            
            
            Init(Host,Post);
            Conn();
            // CharacterInputSystem.Inst._playerInputActions.L_Atk.started += (_) =>
            // {
            //     // _netAsyncMgr.Release();
            //     Test();
            // };
            
            // CharacterInputSystem.Inst._playerInputActions.R_Atk.started += (_) =>
            // {
            //     Debug.Log("开始重连");
            //     _netAsyncMgr.ReConnect();
            // };
        }
        
        public void Init(string host,int post)
        {
            _netAsyncMgr.InitLister();
            _netAsyncMgr.Host = host;
            _netAsyncMgr.Port = post;
            
            SystemMessageHandle.AddAllListener();
            RunTimeMessageHandle.AddAllListener();
        }

        public void Conn() => _netAsyncMgr.Connect(_netAsyncMgr.Host, _netAsyncMgr.Port);
        
        //异步的请求方法
        public async Task<ResponseResult> RequestSendAsync(string funcName,params object[] args)
        {
            // 构建一个消息
            var msg = MessagePool.GetRequestMessage();
            msg.Data.Seq = _seq++;
            _seq = _seq % Int32.MaxValue;
            msg.Data.FuncName = funcName;
            //作为一个用户标识上传
            msg.Data.FuncArgs = $"{_netAsyncMgr.ClientID},";
            msg.Data.FuncArgs = ConvertParamsToString(args);
            _netAsyncMgr.Send(msg);
            return await ResponseResultContainer.WaitForResponseAsync(msg.Data.Seq, TimeSpan.FromSeconds(5));
        }

        private void Update()
        {
            _netAsyncMgr.Update();
        }

        protected override void Release()
        {
            _netAsyncMgr.Release();
        }

        private string ConvertParamsToString(params object[] args)
        {
            List<string> argStrings = new List<string>();

            foreach (var arg in args)
            {
                // 获取参数的类型
                string type = arg.GetType().Name;
                // 获取参数的值（确保字符串值被正确地转义）
                string value = arg is string ? $"\"{arg}\"" : arg.ToString();
                // 组合类型和值
                string argString = $"{type}:{value}";
                // 添加到列表中
                argStrings.Add(argString);
            }

            // 将所有参数字符串连接成一个单一的字符串
            return string.Join(",", argStrings);
        }


        // private async void Test()
        // {
        //     switch (TestProjectID)
        //     {
        //         case 0:
        //             var result1 = await RequestSendAsync("GameLogic:Login", "11111111112", "21112", "11111");
        //             Text.text = string.Format("执行结果\nErrorCode:{0}\nResult:{1}", result1.ErrorCode, result1.Result);
        //             Debug.Log(result1.Result);
        //             break;
        //         case 1:
        //             var result2 = await RequestSendAsync("GameLogic:test","21112", "11111");
        //             Text.text = string.Format("执行结果\nErrorCode:{0}\nResult:{1}", result2.ErrorCode, result2.Result);
        //             Debug.Log(result2.Result);
        //             break;
        //         case 2:
        //             var result3 = await RequestSendAsync("GameLogic:Login",11111, "11111");
        //             Text.text = string.Format("执行结果\nErrorCode:{0}\nResult:{1}", result3.ErrorCode, result3.Result);
        //             Debug.Log(result3.Result);
        //             break;
        //         case 3:
        //             var result4 = await RequestSendAsync("GameLogic:GetInfo");
        //             Text.text = string.Format("执行结果\nErrorCode:{0}\nResult:{1}", result4.ErrorCode, result4.Result);
        //             Debug.Log(result4.Result);
        //             break;
        //         case 4:
        //             var result6 = await RequestSendAsync("GameLogic:Test3");
        //             Text.text = string.Format("执行结果\nErrorCode:{0}\nResult:{1}", result6.ErrorCode, result6.Result);
        //             Debug.Log(result6.Result);
        //             break;
        //         case 5:
        //             _netAsyncMgr.Release();
        //             Text.text = ("执行结果\n已断开连接");
        //             break;
        //         case 6:
        //             _netAsyncMgr.ReConnect();
        //             Text.text = ("执行结果\n尝试重新链接");
        //             break;
        //     }
        // }
    }
}